import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { getToken } from '@/utils/auth'
import router from '@/router'
// let token = getToken()
// 创建 axios 实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  // baseURL: 'http://127.0.0.1:10002/api/manage', // api base_url
  // baseURL: 'http://127.0.0.1:8091', // api base_url
  baseURL: 'http://139.9.183.72:8003/api/manage', // api base_url
  timeout: 60000000 // 请求超时时间
})

const err = (error) => {
  console.log('请求失败', error)
  if (error.response) {
    const data = error.response.data

    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      if (getToken()) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  if (getToken()) {
    config.headers['token'] = getToken() // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  const res = response.data
  console.log(response)
  if (res.code) {
    if (res.code !== 200) {
      // 50008:非法的token; 50012:其他客户端登录了;  401:Token 过期了;
      if (res.code === 50008 || res.code === 50012 || res.code === 401) {
        notification.error({
          message: '权限失效',
          description: '你已被登出需重新登录,3秒后将返回到登录页面'
        })

        /* Notification({
         title: '提示',
         message: '你已被登出需重新登录,3秒后将返回到登录页面',
         type: 'error',
         duration: 3000
         }) */

        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            // window.location.reload()
            router.push('/user/login')
          }, 2000)
        })
      } else if (res.code === 500) {
        notification.error({
          message: 'cood = 500',
          description: res.msg
        })
      } else {
        notification.error({
          message: '请求发生错误',
          description: res.msg
        })
      }
      return Promise.reject('error')
    } else {
      return response.data
    }
  } else {
    console.log(response)
    // notification.error({
    //   message: 'cood为' + res.code,
    //   description: "请求错误，请检查api"
    // })
    return response.data
  }

  // return response.data
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
